package com.customization.quanshimeting;


import aiyh.utils.Util;
import aiyh.utils.zwl.common.ToolUtil;
import com.engine.core.cfg.annotation.ServiceDynamicProxy;
import com.engine.core.cfg.annotation.ServiceMethodDynamicProxy;
import com.engine.core.impl.aop.AbstractServiceProxy;
import com.engine.meeting.service.MeetingBaseService;
import com.engine.meeting.service.impl.MeetingBaseServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import weaver.aiyh_quanshi.RequestApi;
import weaver.aiyh_quanshi.entity.QsConfParty;
import weaver.aiyh_quanshi.entity.QsResponse;
import weaver.conn.RecordSet;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author EBU7-dev1-ayh
 * @create 2021/9/17 0017 16:18
 * 代理类
 */

@ServiceDynamicProxy(target = MeetingBaseServiceImpl.class, desc = "对全时会议进行同步")
public class NewMeetingServiceProxy extends AbstractServiceProxy implements MeetingBaseService {
	private final ToolUtil toolUtil = new ToolUtil();
	private final RequestApi requestApi = new RequestApi();
	private final SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");


	@Override
	@ServiceMethodDynamicProxy(desc = "创建会议，向全时会议中添加预约会议")
	public Map<String, Object> newMeeting(Map<String, Object> map) {

		toolUtil.writeErrorLog(map.toString());
		try {
			int quanShiType = Integer.parseInt(Util.null2String("".equals(toolUtil.getSystemParamValue("QUAN_SHI_TYPE")) ? null : toolUtil.getSystemParamValue("QUAN_SHI_TYPE"), "-1"));
			int meetingType = Integer.parseInt(Util.null2String("".equals(String.valueOf(map.get("meetingtype"))) ? null : String.valueOf(map.get("meetingtype")), "0"));
			if (quanShiType != meetingType) {
				return (Map<String, Object>) executeMethod(map);
			}
		} catch (Exception e) {
			toolUtil.writeErrorLog("转换失败，失败原因：" + e);
			return (Map<String, Object>) executeMethod(map);
		}
		Map<String, Object> result = (Map<String, Object>) executeMethod(map);
		//		获取会议标题
		String title = String.valueOf(map.get("name"));
//		会议内容
		String desc_n = String.valueOf(map.get("desc_n"));
//		获取会议创建人
		String creator = String.valueOf(map.get("contacter"));
		RecordSet rs = new RecordSet();
//		获取会议创建人邮件
		String query = "select * from hrmresource where id = ?";
		rs.executeQuery(query, creator);
		rs.next();
		String creatorEmail = rs.getString("email");
		//		获取会议开始日期
		String startDate = String.valueOf(map.get("begindate"));
//		获取会议开始时间
		String startTime = String.valueOf(map.get("begintime"));
		Date start;
		try {
			start = simpleFormat.parse(startDate + " " + startTime);
		} catch (ParseException e) {
/*			e.printStackTrace();
			Map<String, Object> resultErr = new HashMap<>();
//				请求失败
			resultErr.put("status", false);
			resultErr.put("retstatus", true);
			resultErr.put("error", "日期转换失败！");
			resultErr.put("msg", "日期转换失败！");
			resultErr.put("api_errormsg", "日期转换失败！");
			return resultErr;*/
			return result;
		}

//		获取会议结束日期
		String endDate = String.valueOf(map.get("enddate"));
//		获取会议结束时间
		String endTime = String.valueOf(map.get("endtime"));
		Date end;
		try {
			end = simpleFormat.parse(endDate + " " + endTime);
		} catch (ParseException e) {
/*			e.printStackTrace();
			Map<String, Object> resultErr = new HashMap<>();
//				请求失败
			resultErr.put("status", false);
			resultErr.put("retstatus", true);
			resultErr.put("error", "日期转换失败!");
			resultErr.put("msg", "日期转换失败！");
			resultErr.put("api_errormsg", "日期转换失败！");
			return resultErr;*/
			return result;
		}
//		计算会议时长
		int length = new Long((end.getTime() - start.getTime()) / (1000 * 60)).intValue();
//		获取会议参与人
		String hrmStr = String.valueOf(map.get("hrmmembers"));
//	    处理会议参与人
		List<QsConfParty> list = new ArrayList<>();
		List<String> emailList = new ArrayList<>();
		query = "select * from hrmresource where id in ( " + hrmStr + ")";
		rs.executeQuery(query);
		while (rs.next()) {
			QsConfParty qsConfParty = new QsConfParty();
			qsConfParty.setEmail(rs.getString("email"));
			emailList.add(rs.getString("email"));
			list.add(qsConfParty);
			if (emailList.size() == 199) {
				QsResponse userIdsByEmails = requestApi.getInfoByEmail(emailList);
				Map<String, Object> resultMap = new HashMap<>();

				ObjectMapper mapper = new ObjectMapper();
				try {
					resultMap = mapper.readValue(userIdsByEmails.getResult(), Map.class);
				} catch (JsonProcessingException e) {
					toolUtil.writeErrorLog(userIdsByEmails.toString());
					toolUtil.writeErrorLog("请求结果转换失败，失败信息：" + e);
				}
				for (QsConfParty confParty : list) {
					confParty.setUserId(Long.valueOf(String.valueOf(((Map<String, Object>) resultMap.get(confParty.getEmail())).get("userId"))));
				}
				emailList.clear();
			}
		}
		QsResponse userIdsByEmails = requestApi.getInfoByEmail(emailList);
		Map<String, Object> resultsMap = new HashMap<>();

		ObjectMapper mapper = new ObjectMapper();
		try {
			resultsMap = mapper.readValue(userIdsByEmails.getResult(), Map.class);
		} catch (JsonProcessingException e) {
			toolUtil.writeErrorLog(userIdsByEmails.toString());
			toolUtil.writeErrorLog("请求结果转换失败，失败信息：" + e);
		}
		for (QsConfParty confParty : list) {
			confParty.setUserId(Long.valueOf(String.valueOf(((Map<String, Object>) resultsMap.get(confParty.getEmail())).get("userId"))));
		}
/*		toolUtil.writeErrorLog(list.toString());
		toolUtil.writeErrorLog(creatorEmail);
		toolUtil.writeErrorLog(title);
		toolUtil.writeErrorLog(String.valueOf(length));
		toolUtil.writeErrorLog(startDate + " " + startTime + ":00 ");*/
		QsResponse meeting = requestApi.createMeting(creatorEmail, title, length, startDate + " " + startTime + ":00", list);
		if (meeting != null) {
			if (!"0".equals(meeting.getStatus())) {
				String update = "update meeting set quanshimeeting = ? where id = ?";
				rs.executeUpdate(update, "全时会议添加失败！", String.valueOf(map.get("meetingid")));
				toolUtil.writeErrorLog(meeting.toString());
/*				Map<String, Object> result = new HashMap<>();
//				请求失败
				result.put("status", false);
				result.put("retstatus", false);
				result.put("error", "全时会议添加失败");
				result.put("msg", "全时会议添加失败！");
				result.put("api_errormsg", "全时会议添加失败！");
				return result;*/
				return result;
			} else {
//				请求成功
				Map<String, Object> resultMap = new HashMap<>();

				try {
					resultMap = mapper.readValue(meeting.getResult(), Map.class);
				} catch (JsonProcessingException e) {
					toolUtil.writeErrorLog("请求结果转换失败，失败信息：" + e);
				}
				if (Boolean.parseBoolean(String.valueOf(result.get("status")))) {
//                  添加成功
					String update = "update meeting set quan_shi_id = ?, quanshimeeting = ? where id = ?";
					String quanShjInfo = "会议密码：" + String.valueOf(resultMap.get("pcode2")) + "<br /><br />会议连接：" + String.valueOf(resultMap.get("attendeeJoinUrl"));
					rs.executeUpdate(update, String.valueOf(resultMap.get("conferenceId")), quanShjInfo, String.valueOf(map.get("meetingid")));
					return result;
				} else {
					QsResponse qsResponse = requestApi.cancelConference(String.valueOf(resultMap.get("conferenceId")), creatorEmail);
					toolUtil.writeErrorLog(qsResponse.toString());
/*					Map<String, Object> resultErr = new HashMap<>();
//				请求失败
					resultErr.put("status", false);
					resultErr.put("retstatus", false);
					resultErr.put("error", "OA会议添加失败！");
					resultErr.put("msg", "OA会议添加失败！");
					resultErr.put("api_errormsg", "OA会议添加失败！");
					return resultErr;*/
					return result;
				}
			}
		} else {
/*			Map<String, Object> resultErr = new HashMap<>();
//				请求失败
			resultErr.put("status", false);
			resultErr.put("retstatus", false);
			resultErr.put("error", "全时会议添加失败");
			resultErr.put("msg", "全时会议添加失败！");
			resultErr.put("api_errormsg", "全时会议添加失败！");
			return resultErr;*/
			return result;
		}
	}
/*
	Map<String, Object> result = (Map<String, Object>) executeMethod(map);
		if (Boolean.parseBoolean(String.valueOf(result.get("status")))) {
//			会议添加成功，需要王全时会议中添加会议
		String meetingId = String.valueOf(result.get("meetingid"));
//			通过会议id获取到会议相关的信息
		String query = "select * from meeting where id = ?";
		RecordSet rs = new RecordSet();
		rs.executeQuery(query, meetingId);
		MeetingInfoDTO meetingInfoDTO = Util.recordeSet2Entity(rs, MeetingInfoDTO.class, true);
//			判断是否需要对会议进行全时会议添加
		int quanShiType = Integer.parseInt(Util.null2String(toolUtil.getSystemParamValue("QUAN_SHI_TYPE"), "-1"));
		if (meetingInfoDTO.getMeetingtype() != quanShiType) {
			return result;
		}
//			通过信息查询全时会议所需要的数据
//			获取创建人邮箱
		query = "select email from hrmresource where id = ?";
		rs.executeQuery(query, meetingInfoDTO.getCreater());
		rs.next();
		String creatorEmail = rs.getString("email");
//			获取参与人邮箱
		List<QsConfParty> list = new ArrayList<>();
		query = "select email from hrmresource where id in ( " + meetingInfoDTO.getHrmmembers() + ")";
		rs.executeQuery(query);
		while (rs.next()) {
			QsConfParty qsConfParty = new QsConfParty();
			qsConfParty.setEmail(rs.getString("email"));
			list.add(qsConfParty);
		}
//			获取开始i时间和结束时间以及计算会议时长
		int length = 0;
		String startDate = "";
		String startTime = "";
		try {
//		        获取会议开始日期
			startDate = String.valueOf(meetingInfoDTO.getBegindate());
//		        获取会议开始时间
			startTime = String.valueOf(meetingInfoDTO.getBegintime());
			Date start = simpleFormat.parse(startDate + " " + startTime);
//		        获取会议结束日期
			String endDate = String.valueOf(meetingInfoDTO.getEnddate());
//		        获取会议结束时间
			String endTime = String.valueOf(meetingInfoDTO.getEndtime());
			Date end = simpleFormat.parse(endDate + " " + endTime);
//		        计算会议时长
			length = new Long((end.getTime() - start.getTime()) / (1000 * 60)).intValue();
		} catch (Exception e) {
			toolUtil.writeErrorLog("日期传换失败，失败信息：" + e);
		}
//		    调取接口
		QsResponse meting = requestApi.createMeting(creatorEmail, meetingInfoDTO.getName(), length, startDate + " " + startTime + ":00 ", list);
		if (!"0".equals(meting.getStatus())) {
			toolUtil.writeErrorLog("全时会议添加失败！失败结果" + meting);
//				需要删除OA会议
//				添加全时会议失败
			result.put("status", false);
			result.put("retstatus", false);
			result.put("error", "全时会议添加失败");
			result.put("msg", "全时会议添加失败！");
			result.put("api_errormsg", "abab全时会议添加失败！");
			result.remove("apiCost");
			result.remove("meetingid");
		} else {
//				添加全时会议成功
			String update = "update meeting set quan_shi_id = ? where id = ?";
			Map<String, Object> resultMap = new HashMap<>();
			ObjectMapper mapper = new ObjectMapper();
			try {
				resultMap = mapper.readValue(meting.getResult(), Map.class);
			} catch (JsonProcessingException e) {
				toolUtil.writeErrorLog("请求结果转换失败，失败信息：" + e);
			}
			rs.executeUpdate(update, String.valueOf(resultMap.get("conferenceId")), String.valueOf(map.get("meetingid")));
		}
	}
//		throw new RuntimeException("全时会议添加失败!");
		return result;*/

	@Override
	@ServiceMethodDynamicProxy(desc = "删除会议时， 需要判断是否需要对全时会议的会议进行取消预约")
	public Map<String, Object> deleteMeeting(Map<String, Object> map) {
		Map<String, Object> result = (Map<String, Object>) executeMethod(map);
//		获取请求参数中的会议id
		String meetingIds = String.valueOf(map.get("meetingids"));
//		查询要删除的会议中是否存再全时会议预约的，如果有需要对全时会议进行取消
		String query = "select * from meeting where id in (" + meetingIds + ") and cancel != 1 and quan_shi_id is not null and quan_shi_cancel is null";
		RecordSet rs = new RecordSet();
		rs.executeQuery(query);
		RecordSet rs_1 = new RecordSet();
		while (rs.next()) {
//			取消会议
			String quanShiId = rs.getString("quan_shi_id");
			String hrmId = rs.getString("contacter");
			query = "select * from hrmresource where id = ?";
			rs_1.executeQuery(query, hrmId);
			rs_1.next();
			String creatorEmail = rs_1.getString("email");
			QsResponse qsResponse = requestApi.cancelConference(quanShiId, creatorEmail);
			if (!"0".equals(qsResponse.getStatus())) {
//				取消失败
				toolUtil.writeErrorLog("全时会议取消失败！失败结果" + qsResponse);
				/*Map<String, Object> resultErr = new HashMap<>();
				resultErr.put("status", false);
				resultErr.put("retstatus", false);
				resultErr.put("ret", false);
				resultErr.put("error", "全时会议取消失败！");
				resultErr.put("msg", "全时会议取消失败！");
				resultErr.put("api_errormsg", "全时会议取消失败！");
				return resultErr;*/
				return result;
			} else {
				String update = "update meeting set quan_shi_cancel = ? where id = ?";
				rs_1.executeUpdate(update, "1", rs.getString("id"));
			}
		}
//		取消成功，需要删除OA中会议
//		Map<String, Object> result = (Map<String, Object>) executeMethod(map);
		return result;
	}

	@Override
	public Map<String, Object> editMeeting(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> overMeeting(Map<String, Object> map) {
		return null;
	}

	@Override
	@ServiceMethodDynamicProxy(desc = "取消会议时，需要对全时会议的会议也进行同步取消")
	public Map<String, Object> cancelMeeting(Map<String, Object> map) {
		String meetingId = String.valueOf(map.get("meetingid"));
		//			通过会议id获取到会议相关的信息
		String query = "select * from meeting where id = ?";
		RecordSet rs = new RecordSet();
		rs.executeQuery(query, meetingId);
		rs.next();
		String quanShiId = rs.getString("quan_shi_id");
		Map<String, Object> result = (Map<String, Object>) executeMethod(map);
		int quanShiType = Integer.parseInt(Util.null2String(toolUtil.getSystemParamValue("QUAN_SHI_TYPE"), "-1"));
		if (rs.getInt("meetingtype") != quanShiType) {
			return result;
		}
		RecordSet rs_1 = new RecordSet();
//			取消会议
		String hrmId = rs.getString("contacter");
		query = "select * from hrmresource where id = ?";
		rs_1.executeQuery(query, hrmId);
		rs_1.next();
		String creatorEmail = rs_1.getString("email");
		QsResponse qsResponse = requestApi.cancelConference(quanShiId, creatorEmail);
		if (!"0".equals(qsResponse.getStatus())) {
//				取消失败
			toolUtil.writeErrorLog("全时会议取消失败！失败结果" + qsResponse);
			/*Map<String, Object> resultErr = new HashMap<>();
			resultErr.put("status", false);
			resultErr.put("retstatus", false);
			resultErr.put("ret", false);
			resultErr.put("error", "全时会议取消失败！");
			resultErr.put("msg", "全时会议取消失败！");
			resultErr.put("api_errormsg", "全时会议取消失败！");
			return resultErr;*/
			return result;
		} else {
			String update = "update meeting set quan_shi_cancel = ? where id = ?";
			rs_1.executeUpdate(update, "1", rs.getString("id"));
		}
		return result;
	}

	@Override
	public Map<String, Object> chkMember(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> chkRoom(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> chkservice(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> chkRoomAttribute(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> chkWPMember(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> updateCkIsck(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> chkMeeting(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> customMeetingChk(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> changeMeeting(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> submitMeeting(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> afterMeetingNormal(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> afterMeetingChange(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> getUnReadCount(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> doSubmit(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> selRejectNode(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> doReject(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> getUserDefInfo(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> getNowMeeting(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> getMoreMeeting(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> getMeetingCornerMark(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> getRequestParams(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> exportExcel(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> chkRight(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> customChangeHrm(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> getMeetingTabElement(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> chkRepeatMeeting(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> afterMeetingDelete(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> meetingToGovern(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> meetingDecisionToGovern(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> getMeetingInfluenceInfo(String s) {
		return null;
	}

	@Override
	public Map<String, Object> getMeetingSysWorkRecordList(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> getDefalutByLevel(Map<String, Object> map) {
		return null;
	}

	@Override
	public Map<String, Object> getMeetingBaseInfo(Map<String, Object> map) {
		return null;
	}
}
